/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.action;

import able.stripes.JSP;
import exatrez.stripes.Configuration;
import exatrez.dao.GalleryDAO;
import com.google.inject.Inject;
import exatrez.stripes.BaseActionBean;
import exatrez.stripes.config.AuthRequired;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import exatrez.model.Gallery;
import exatrez.manager.GalleryManager;
import exatrez.model.User;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.sourceforge.stripes.action.FileBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.StreamingResolution;

/**
 *
 * @author zulfadli
 */
@UrlBinding("/gallery")
@AuthRequired
public class GalleryAction extends BaseActionBean {

    //for thumbnails
    private static final int IMG_WIDTH = 100;
    private static final int IMG_HEIGHT = 100;
    @Inject
    Configuration conf;
    private static Logger LOG = LoggerFactory.getLogger(GalleryAction.class);
    private Gallery picture;
    private FileBean fileBean;
    private String month;
    @Inject
    private GalleryManager galleryManager;
    private List<Gallery> gallery;
    private List<Gallery> galleryAll;
    private List<Gallery> randomGal;
    @Inject
    private GalleryDAO galleryDAO;

    public List<Gallery> getRandomGal() {
        return randomGal;
    }

    public void setRandomGal(List<Gallery> randomGal) {
        this.randomGal = randomGal;
    }

    public List<Gallery> getGallery() {
        return gallery;
    }

    public void setGallery(List<Gallery> gallery) {
        this.gallery = gallery;
    }

    public List getGalleryAll() {
        return galleryAll;
    }

    public void setGalleryAll(List<Gallery> galleryAll) {
        this.galleryAll = galleryAll;
    }

    public FileBean getFileBean() {
        return fileBean;
    }

    public void setFileBean(FileBean fileBean) {
        this.fileBean = fileBean;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public Gallery getPicture() {
        return picture;
    }

    public void setPicture(Gallery picture) {
        this.picture = picture;
    }

    @DefaultHandler
    public Resolution index() {
        LOG.debug("masuk gallery index");
        galleryAll = galleryManager.findAll();
        randomGal = galleryManager.getRandomGallery();
        return new JSP("gallery/main.jsp");
    }

    public Resolution upload() {
        picture = new Gallery();
        return new JSP("gallery/upload.jsp");
    }

    public Resolution uploadImage() throws IOException {
        LOG.debug("upload process started");
        String path = conf.getProperty("gallery.path");
        User user = getContext().getCurrentUser();
        //create unique filename
        String newname = System.currentTimeMillis() / 1000 + "";
        //get uploaded file extension
        //String extension = fileBean.getContentType().substring(fileBean.getContentType().length() - 3);
        //create thumbnails
        //add some checking if there is no related folder (vessel, thumbs), create it
        LOG.debug("check directory whether exist");
        File dir = new File(path + picture.getVessel().getVesselId() + File.separator + picture.getYear() + File.separator + month + File.separator + "thumbs" + File.separator);
        if (!dir.exists()) {
            LOG.debug("directory not exist, creating..");
            boolean dirIsCreated = dir.mkdirs();
            if (dirIsCreated) {
                LOG.debug("directory successfully created.");
            }
        }
        //checking that only image can be upload and the file must be jpg file
        LOG.debug(fileBean.getContentType());
        if(!fileBean.getContentType().matches("image/jpeg|image/png|image/bmp")){
            LOG.error("user try to upload file with different mimetype");
            addSimpleError("Only image files with file type JPEG, BMP & PNG is allowed to be uploaded.");
            return upload();
        }
        BufferedImage originalImage = ImageIO.read(fileBean.getInputStream());
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizeImageJpg = resizeImage(originalImage, type);
        ImageIO.write(resizeImageJpg, "jpg", new File(path + picture.getVessel().getVesselId() + File.separator + picture.getYear() + File.separator + month + File.separator + "thumbs" + File.separator + newname + ".jpg"));
        //save the file
        ImageIO.write(originalImage, "jpg", new File(path + picture.getVessel().getVesselId() + File.separator + picture.getYear() + File.separator + month + File.separator + newname + ".jpg"));
        //set the path
        picture.setDocumentPath(picture.getVessel().getVesselId() + File.separator + picture.getYear() + File.separator + month + File.separator+newname + ".jpg");
        picture.setFilename(newname + ".jpg");
        picture.setMonth(month);
        picture.setUploadedBy(user.getUserId());
        galleryManager.saveOrUpdate(picture);
        //delete temp file
        fileBean.delete();
        //add some message
        addSimpleMessage("Upload Success");
        return upload();
    }

    private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();

        return resizedImage;
    }

    public Resolution image() throws IOException {
        return new StreamingResolution("image/jpeg") {
            public void stream(final HttpServletResponse response) throws FileNotFoundException {
                String path = conf.getProperty("gallery.path");
                String id = getContext().getRequest().getParameter("galleryId");
                //String thumb = getContext().getRequest().getParameter("thumb");
                Gallery pct = galleryManager.getGallery(id);

                //File file = new File("/home/zulfadli/upload/1/2013/thumbs/1369295955.jpg");
                File file = new File(path+pct.getDocumentPath());


                //InputStream sample = new FileInputStream(file);
                InputStream sample = new FileInputStream(file);
                //InputStream sample = null;
                try {
                    //sample = getResourceAsStream(SAMPLE + getContext().getLocale().toString());
                    //if (sample == null) sample = getResourceAsStream(SAMPLE + "en_US");

                    final OutputStream out = response.getOutputStream();
                    final byte buffer[] = new byte[8192];

                    //out.write((HEADER + "\n").getBytes());

                    for (int rc = sample.read(buffer); rc > 0; rc = sample.read(buffer)) {
                        out.write(buffer, 0, rc);
                    }
                } catch (IOException e) {
                } finally {
                    if (sample != null) {
                        try {
                            sample.close();
                        } catch (IOException ioe) {
                        }
                    }
                }
            }
        };
    }

    public Resolution showGallery() {
        String vessel = getContext().getRequest().getParameter("vessel");
        String year = getContext().getRequest().getParameter("year");
        gallery = galleryManager.getGalleryYear(vessel, year);
        //return new JSP("gallery/main.jsp");
        return index();
    }

    public Resolution deletePicture() {
        String galleryId = getContext().getRequest().getParameter("galleryId");
        if (galleryId != null) {
            Gallery gal = galleryDAO.findById(Integer.valueOf(galleryId));
            if (gal != null) {
                galleryManager.deleteGallery(gal);
            }
        }
        return null;
    }
}
